package com.classic.okhttp.zmoumall.http;

import android.content.Context;

import com.classic.okhttp.base.OkHttpUtils;
import com.classic.okhttp.base.callback.StringCallback;
import com.classic.okhttp.zmoumall.utils.NetworkUtil;
import com.classic.okhttp.zmoumall.utils.ToastUtil;
import com.google.gson.Gson;
import com.orhanobut.logger.Logger;

import org.json.JSONObject;

import java.lang.reflect.Type;

/**
 * 通用对象解析
 * <pre>使用Gson进行解析</pre>
 * ltx
 */
public abstract class ObjectCallback<T> extends StringCallback {

    private static final int SUCCESS_CODE = 0;
    private static final int LOGIN_OTHER_CODE = 201;
    private static final int NO_NET_WORK = -100;//无网络的情况
    private static final String S_NO_NET_WORK = "当前无网络，请重试";//无网络的情况
    private static final String KEY_CODE = "ErrorCode";
    private static final String KEY_OBJECT = "Data";
    private static final String KEY_ERROR = "Message";
    private static final String TIME_OUT = "timeout";
    private static final String TIME_OUT_STR = "请求超时，稍后重试";
    private Type type;//gson 初始化

    private String cachekey;//缓存的key

    private ACache mACache;//缓存

    private Context mContext;

    private boolean isCache;

    public void setCallBackBean(Type t) {
        type = t;
    }

    private T obj = null;

    /**
     * 缓存相关
     *
     * @param mACache  缓存实体类
     * @param cachekey 缓存key
     * @param isCache  是否需要缓存
     */
    public void setACache(ACache mACache, String cachekey, boolean isCache) {
        this.mACache = mACache;
        this.cachekey = cachekey;
        this.isCache = isCache;
    }

    /**
     * 设置上下文
     *
     * @param mContext 上下文
     */
    public void setContext(Context mContext) {
        this.mContext = mContext;
    }


    @Override
    public void onSuccess(String json) {
        try {
            if (null == json || "".equals(json) || json.length() == 0 || json.equals("null")) {
                onError(OkHttpUtils.DEFAULT_ERROR_CODE, "");
                Logger.e("Error", "数据为空");
                return;
            }
            final int code = new JSONObject(json).getInt(KEY_CODE);
            if (code == SUCCESS_CODE) {
                final String message = new JSONObject(json).getString(KEY_ERROR);

                if (!json.contains(KEY_OBJECT)) {
                    onSuccess(null, message);
                } else {
                     String content = new JSONObject(json).getString(KEY_OBJECT);
                    //如果是String 就直接返回不需要解析
                    if(type ==String.class){
                        obj= (T) content;
                    }else{
                     obj = new Gson().fromJson(content, type);
                    }
                    onSuccess(obj, message);
                    if (isCache) {//是否需要缓存
                        mACache.put(cachekey, content, ACache.TIME_DAY);
                    }
                    Logger.i("OnSuccess", content);
                }

            } else if (code == LOGIN_OTHER_CODE) {
                final String content = new JSONObject(json).getString(KEY_ERROR);
               /* CarApplication.otherLogin(content);*/
                Logger.i("OnError", content);
            } else {//服务器返回错误 解析bean
                String messgae = new JSONObject(json).getString(KEY_ERROR);
                if(json.contains(KEY_OBJECT)){
                    String content=new JSONObject(json).getString(KEY_OBJECT);
                    onError(code,content, messgae);
                }else{
                    onError(code,null, messgae);
                }
                Logger.i("OnError", messgae);
            }
        } catch (Exception e) {
            onError(OkHttpUtils.DEFAULT_ERROR_CODE, e.toString());
            e.printStackTrace();
        }
    }

    public abstract void onSuccess(T response, String message);

    public abstract void onErrorT(int code, T response, String errorMessage);

    @Override
    public void onError(int code, String content,String errorMessage) {
        super.onError(code,content,errorMessage);
        Logger.e(errorMessage);
        if (!NetworkUtil.isNetworkAvailable(mContext)) {
            ToastUtil.showToast(mContext, S_NO_NET_WORK);
            if (isCache) {//有缓存的时候添加缓存
                final String contentCache = mACache.getAsString(cachekey);
                T obj = new Gson().fromJson(contentCache, type);
                onErrorT(NO_NET_WORK, obj, S_NO_NET_WORK);
            }
            onErrorT(NO_NET_WORK, null, S_NO_NET_WORK);
        } else{
            if(type ==String.class){
                obj= (T) content;
            }else{
                obj = new Gson().fromJson(content, type);
            }
            if(null!=errorMessage&&(errorMessage.contains("Connection reset by peer")||errorMessage.equals("failed to"))){//解决有网络但不能上网的情况
                onErrorT(NO_NET_WORK, obj, S_NO_NET_WORK);

            }else{
                onErrorT(code, obj, errorMessage);

            }
        }
        if(TIME_OUT.equals(errorMessage)){//网络超时
            ToastUtil.showToast(mContext,TIME_OUT_STR);
        }
    }
}
